/* 
 * File:   pgm.hpp
 * Author: gustavo
 *
 * Created on August 28, 2012, 3:39 AM
 */

#ifndef PGM_HPP
#define	PGM_HPP

namespace imp {
	namespace img {

		template <typename T> Image<T> imread_pgm(const char * fname) {

			int width;
			int height;
			int idx;
			int size;
			int max_value;
			char ch;
			int ret;

			FILE * file;
			Image<T> * img;

			file = fopen(fname, "rb");

			if (file == 0) {
				fclose(file);
				__error("File binary open error.");
			}

			/* Ler cabecalho */
			if (fscanf(file, "P%c\n", &ch) != 1 || ch != '5') {
				fclose(file);
				__error("Invalid file.");
			}

			/* Desconsidera comentarios */
			ch = getc(file);
			while (ch == '#') {
				do {
					ch = getc(file);
				} while (ch != '\n'); /* Le ate o final da linha */
				ch = getc(file);
			}
			ungetc(ch, file);
			ret = fscanf(file, "%d %d\n", &width, &height);
			/* idx esta funcionando como uma variavel inteira temportaria */
			ret = fscanf(file, "%d\n", &idx);
			max_value = idx;

			/* Salva os parametros da imagem */
			img = new Image<T> (width, height, 1);

			if (img == NULL) {
				fclose(file);
				__error("Unable to alloc memory to image.");
			}

			/* Leitura dos pixels */
			size = width * height;
			for (idx = 0; idx < size; idx++) {
				ret = fread(&ch, sizeof (char), 1, file);
				img->data[idx] = (T) ch;
			}

			fclose(file);
			return *img;

		}

		template <typename T> int imsave_pgm(Image<T>& img, const char * fname) {
			FILE* fp;

			int width = img.width;
			int height = img.height;
			T * data = img.data;

			if ((fp = fopen(fname, "w")) == NULL) {
				__error("Could not open file %s for writing.", fname);
			}

			fprintf(fp, "P5\n# CREATOR: ImpPack.\n%d %d\n255\n", width, height);

			int index;
			int size = width * height;
			for (index = 0; index < size; ++index) {
				putc(data[index], fp);
			}

			fflush(fp);
			fclose(fp);
			return 1;
		}

	}
}


#endif	/* PGM_HPP */

